﻿using System;
using System.Linq;
using System.Windows;

using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace GroupChallengeWP7
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            // Provide a pointer to the main UI.
            App.TheMainPage = this;

            InitializeComponent();

            SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            // Load data for the ViewModel Items
            InitPage();
        }

        private void InitPage()
        {
            if (!App.ViewModel.InGame)
                PivotContainer.SelectedIndex = 2;
            else
                PivotContainer.SelectedIndex = 0;

        }

        private void PivotContainer_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            bool joinPivot = (PivotContainer.SelectedIndex == 2);
            ApplicationBar.IsVisible = joinPivot;
        }

        private void JoinButton_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            ApplicationBarIconButton joinButton = ApplicationBar.Buttons
                .OfType<ApplicationBarIconButton>()
                .Single(button => button.Text == "join");
            joinButton.IsEnabled = (bool)e.NewValue;
        }

        private void LeaveButton_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            ApplicationBarIconButton leaveButton = ApplicationBar.Buttons
                .OfType<ApplicationBarIconButton>()
                .Single(button => button.Text == "leave");
            leaveButton.IsEnabled = (bool)e.NewValue;
        }

        private void joinButton_Click(object sender, EventArgs e)
        {
            try
            {
                App.ViewModel.JoinGame();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Unable to join the game.  Reason: " + ex.Message, "Join Game Error", MessageBoxButton.OK);
            }
        }

        private void leaveButton_Click(object sender, EventArgs e)
        {
            try
            {
                App.ViewModel.LeaveGame();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to leave the game.  Reason: " + ex.Message, "Leave Game Error", MessageBoxButton.OK);
            }
        }
    }
}
